package com.desheng.util;

import com.desheng.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LZC
 * @create 2021-10-10 23:46
 */
@WebFilter("/*")
public class MyFilter implements Filter {
    public static List<String> pattenURL = new ArrayList<>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //不需要拦截的资源
        pattenURL.add("view/index");
        pattenURL.add("test/login");
        pattenURL.add("view/register");
        pattenURL.add("css");
        pattenURL.add("image");
        pattenURL.add("js");
        pattenURL.add("fonts");
        pattenURL.add("png");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hr = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String url = hr.getRequestURI().toString();
        User user  = (User)hr.getSession().getAttribute("user");
        for(String urlStr:pattenURL){
            if(url.indexOf(urlStr)>-1){
//                System.out.println("不拦截");
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        if(user==null){
//            System.out.println("拦截了");
            response.sendRedirect(hr.getContextPath()+"/view/index");
        }else{
//            System.out.println("放行");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
